package reflect;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
import java.util.Arrays;

/**
 * 实例化与当前类在同一个包中的所以类
 */

public class Test2 {
    //老师写的
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test2.class.getResource(".").toURI()
        );
        System.out.println(dir);
        //添加过滤器获取该目录中的所有字节码文件
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File sub : subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.lastIndexOf("."));
//            String className = fileName.replace(".class","");
            String packName = Test2.class.getPackage().getName();
            className = packName+"."+className;
            Class cls = Class.forName(className);
            Object obj = cls.newInstance();

            Method[] methods = cls.getDeclaredMethods();
            for (Method m : methods) {
                if(m.getParameterCount() == 0 && m.getModifiers() == Modifier.PUBLIC){
                    System.out.println("调用方法:"+m.getName()+"()");
                    m.invoke(obj);
                }
            }

        }

    }
    //自己写的
    public static void main2(String[] args) throws Exception {
        File dir = new File(Test2.class.getResource(".").toURI());

        //获取到包名
        String []dirs = dir.toString().split("\\\\");
        String packageName = dirs[dirs.length-1];

        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        Object [] obj = new Object[subs.length];
        int i = 0;
        for (File f:subs) {
            //获取到文件名
            String []data = f.getName().split(".class");
            Class cls = Class.forName(packageName+"."+data[0]);
            obj[i++] =cls.newInstance();
        }
        for (Object o : obj) {
            System.out.println(o.toString());
        }
    }
}
